﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class Categories : System.Web.UI.Page
{
    CSMSWebService.CSMSWebService csms = new CSMSWebService.CSMSWebService();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!this.IsPostBack)
            {
                Session["searchCategories"] = false;
                try
                {
                    loadData();
                    ViewState["gv"] = gvCategories.DataSource;
                    ViewState["SortDirection"] = "DESC";
                }
                catch (System.Exception ex)
                {
                    Response.Write("<script>alert('" + "LoadDB failed" + "')</script>");
                }
                btnSave.Visible = false;
                btnNew.Visible = true;
                btnAdd.Visible = true;

            }

            gvCategories.DataSource = ViewState["gv"];
            gvCategories.DataBind();

            if ((bool)Session["searchCategories"])
            {
                btnSave.Visible = true;
                btnNew.Visible = true;
                btnAdd.Visible = false;
            }
            else
            {
                btnSave.Visible = false;
                btnNew.Visible = true;
                btnAdd.Visible = true;
            }
            btnSave.Attributes.Add("onclick", "if(!confirm('Are you sure?')) return false;");
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Some thing wrong!" + "')</script>");
        }
       
    }

    protected void loadData(){
        try
        {
            DataTable dt = new DataTable();
            List<CSMSWebService.Category> listCate = csms.GetListCategory().ToList();
            dt.Columns.Add("Category ID");
            dt.Columns.Add("Category Name");
            dt.Columns.Add("Description");
            foreach (var item in listCate)
	        {
                dt.Rows.Add(item.categoryId, item.categoryName, item.description);                
	        }

            gvCategories.DataSource = dt;
            gvCategories.AutoGenerateSelectButton = true;
            gvCategories.AllowPaging = true;
            gvCategories.PageSize = 3;
            gvCategories.DataBind();
            
            if (!this.IsPostBack)
            {
                btnSave.Visible = false;
                btnNew.Visible = true;
                btnAdd.Visible = true;
            }
            ViewState["gv"] = gvCategories.DataSource;
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Load failed" + "')</script>");
            Response.Redirect("404.aspx");
        }
    }
    protected void clear(){
        txtCategoryID.Text = null;
        txtCategoryName.Text = null;
        txtDescription.Text = null;
        txtSearch.Text = null;
        txtSearch.Enabled = true;
        btnSearch.Enabled = true;
        ddlSearchBy.Enabled = true;
        loadData();
    }
    protected void insertCategory()
    {
        try
        {
            CSMSWebService.Category cate = new CSMSWebService.Category();
            cate.categoryName = txtCategoryName.Text;
            cate.description = txtDescription.Text;
            csms.AddNewCategory(cate);
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Add failed" + "')</script>");
        }
        finally
        {
            loadData();
            clear();
        }
        
    }
    protected void updateCategory()
    {
        try
        {
            CSMSWebService.Category cate = new CSMSWebService.Category();
            cate.categoryId = int.Parse(txtCategoryID.Text);
            cate.categoryName = txtCategoryName.Text;
            cate.description = txtDescription.Text;
            csms.UpdateCategory(int.Parse(txtCategoryID.Text), cate);
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Update failed" + "')</script>");
        }
        finally
        {            
            loadData();
            clear();
        }
    }
    protected void deleteCategory()
    {
        try
        {
            CSMSWebService.Category cate = new CSMSWebService.Category();
            cate.categoryId = int.Parse(txtCategoryID.Text);
            cate.categoryName = txtCategoryName.Text;
            cate.description = txtDescription.Text;
            csms.DeleteCategory(int.Parse(txtCategoryID.Text));
            loadData();
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Delete failed" + "')</script>");
        }
        finally
        {
            clear();
        }

    }

    protected void searchBy()
    {
        DataTable dtTmp;
        DataView dv;
        try
        {
            loadData();
            dtTmp = (DataTable) gvCategories.DataSource;
            #region searchmethod
            if (ddlSearchBy.Text.Equals("ID"))
            {
                gvCategories.AutoGenerateSelectButton = true;
                gvCategories.AllowPaging = true;
                gvCategories.PageSize = 3; ;
                dv = new DataView(dtTmp);
                dv.RowFilter = string.Format("[Category ID] = {0}", int.Parse(txtSearch.Text.Trim()));
                gvCategories.DataSource = dv;
                gvCategories.DataBind();
            }
            if (ddlSearchBy.Text.Equals("Category Name"))
            {
                gvCategories.AutoGenerateSelectButton = true;
                gvCategories.AllowPaging = true;
                gvCategories.PageSize = 3;
                dv = new DataView(dtTmp);
                dv.RowFilter = string.Format("[Category Name] LIKE '%{0}%'", txtSearch.Text.Trim());
                gvCategories.DataSource = dv;
                gvCategories.DataBind();
            }
            if (ddlSearchBy.Text.Equals("Description"))
            {
                gvCategories.AutoGenerateSelectButton = true;
                gvCategories.AllowPaging = true;
                gvCategories.PageSize = 3;
                dv = new DataView(dtTmp);
                dv.RowFilter = string.Format("[Description] LIKE '%{0}%'", txtSearch.Text.Trim());
                gvCategories.DataSource = dv;
                gvCategories.DataBind();
            }
            ViewState["gv"] = ((DataView)gvCategories.DataSource).ToTable();
#endregion
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Search failed" + "')</script>");
        }
        finally
        {
            Session["searchCategories"] = true;
        }
        
    }

    protected void gvCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            GridViewRow r = gvCategories.SelectedRow;
            txtCategoryID.Text = Server.HtmlDecode(r.Cells[1].Text);
            txtCategoryName.Text = Server.HtmlDecode(r.Cells[2].Text);
            txtDescription.Text = Server.HtmlDecode(r.Cells[3].Text);
            btnSave.Visible = true;
            btnNew.Visible = true;
            btnAdd.Visible = false;
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Selected index changing failed" + "')</script>");
        }
        
    }
    protected void gvCategories_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            gvCategories.PageIndex = e.NewPageIndex;
            gvCategories.DataSource = ViewState["gv"];
            gvCategories.DataBind();

            txtCategoryID.Text = null;
            txtCategoryName.Text = null;
            txtDescription.Text = null;
            txtSearch.Text = null;
            txtSearch.Enabled = true;
            btnSearch.Enabled = true;
            ddlSearchBy.Enabled = true;

            btnSave.Visible = false;
            btnNew.Visible = true;
            btnAdd.Visible = true;
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Page index changing failed" + "')</script>");
        }
        
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        clear();
        loadData();
        
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        insertCategory();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        updateCategory();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        deleteCategory();
    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {
        searchBy();
    }
    protected void btnReload_Click(object sender, EventArgs e)
    {
        clear();
        loadData();
    }
    protected void gvCategories_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            DataTable dataTable = ViewState["gv"] as DataTable;

            if (dataTable != null)
            {
                DataView dataView = new DataView(dataTable);
                if (ViewState["SortDirection"].ToString().Trim().Equals("ASC"))
                {
                    dataView.Sort = e.SortExpression + " " + "DESC";
                    ViewState["SortDirection"] = "DESC";
                }
                else
                {
                    dataView.Sort = e.SortExpression + " " + "ASC";
                    ViewState["SortDirection"] = "ASC";
                }
                gvCategories.DataSource = dataView;
                gvCategories.DataBind();
                ViewState["gv"] = dataView.ToTable();
            }        
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + "Sort failed" + "')</script>");
        }
        
    }
    
   
}
